package com.example.ercmssystem2.entity;

import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonInclude;

import java.time.LocalDateTime;
import java.time.Duration;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "events")
@JsonIgnoreProperties({"hibernateLazyInitializer"})
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Event {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 100)
    private String title = "";

    @Column(columnDefinition = "TEXT")
    private String description = "";

    @Column(length = 200)
    private String location = "";

    @Column(nullable = false, length = 20)
    private String status = "PENDING"; // PENDING, ASSIGNED, IN_PROGRESS, RESOLVED, CLOSED

    @Column(length = 20)
    private String priority = "MEDIUM"; // LOW, MEDIUM, HIGH, CRITICAL

    // 事件分级：轻微、一般、严重、特大
    @Column(length = 20, nullable = false)
    private String severity = "MODERATE"; // MINOR, MODERATE, SEVERE, CRITICAL

    @ManyToOne
    @JoinColumn(name = "event_type_id", nullable = false)
    @JsonIgnoreProperties({"hibernateLazyInitializer"})
    private EventType eventType;

    @ManyToOne
    @JoinColumn(name = "reporter_id", nullable = false)
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "password", "enabled"})
    private User reporter;

    @ManyToOne
    @JoinColumn(name = "handler_id")
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "password", "enabled"})
    private User handler;

    // 第一响应人
    @ManyToOne
    @JoinColumn(name = "first_responder_id")
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "password", "enabled"})
    private User firstResponder;

    // 计时系统相关字段
    @Column(name = "start_time", nullable = false)
    private LocalDateTime startTime;

    @Column(name = "end_time")
    private LocalDateTime endTime;

    @Column(name = "assigned_time")
    private LocalDateTime assignedTime;

    @Column(name = "in_progress_time")
    private LocalDateTime inProgressTime;

    @Column(name = "resolution_time")
    private LocalDateTime resolutionTime;

    // 事件处理进度
    @Column(name = "progress_percentage")
    private Integer progressPercentage; // 0-100

    @Column(name = "estimated_casualties")
    private Integer estimatedCasualties;

    @Column(name = "actual_casualties")
    private Integer actualCasualties;

    // 事件升级相关
    @Column(name = "escalation_level")
    private Integer escalationLevel; // 0-5级

    // 事件标签
    @Column(length = 500)
    private String tags = "";

    // 事件来源
    @Column(length = 50)
    private String source = "SYSTEM"; // PHONE, SMS, EMAIL, SYSTEM, SOCIAL_MEDIA

    @Column(name = "source_reference")
    private String sourceReference = "";

    @Column(name = "created_at")
    private LocalDateTime createdAt;

    @Column(name = "updated_at")
    private LocalDateTime updatedAt;

    @Column(name = "created_by")
    private Long createdBy;

    // GPS位置信息 - 实际使用
    @Column(name = "current_latitude")
    private Double currentLatitude;

    @Column(name = "current_longitude")
    private Double currentLongitude;

    @Column(name = "last_location_update")
    private LocalDateTime lastLocationUpdate;

    // 响应者状态 - 实际使用
    @Column(name = "responder_status", length = 20)
    private String responderStatus = "ASSIGNED"; // ASSIGNED, ACCEPTED, EN_ROUTE, ARRIVED, IN_PROGRESS, COMPLETED

    @Column(name = "accepted_time")
    private LocalDateTime acceptedTime;

    @Column(name = "en_route_time")
    private LocalDateTime enRouteTime;

    @Column(name = "arrived_time")
    private LocalDateTime arrivedTime;

    @Column(name = "completed_time")
    private LocalDateTime completedTime;

    // 响应时间统计 - 实际使用
    @Column(name = "response_time_minutes")
    private Long responseTimeMinutes; // 从分配到到达的时间

    @Column(name = "processing_time_minutes")
    private Long processingTimeMinutes; // 现场处置时间

    @Column(name = "total_time_minutes")
    private Long totalTimeMinutes; // 总任务时间

    // 安全状态 - 实际使用
    @Column(name = "safety_status", length = 20)
    private String safetyStatus = "SAFE"; // SAFE, CAUTION, DANGER, SOS

    @Column(name = "last_safety_report")
    private LocalDateTime lastSafetyReport;

    // 支援请求 - 实际使用
    @Column(name = "support_requested")
    private Boolean supportRequested = false;

    @Column(name = "support_type")
    private String supportType = ""; // MEDICAL, POLICE, FIRE, SPECIALIST

    @Column(name = "support_request_time")
    private LocalDateTime supportRequestTime;

    // 响应者备注 - 实际使用
    @Column(name = "responder_notes", columnDefinition = "TEXT")
    private String responderNotes = "";

    // 辅助方法
    public Long getResponseTimeMinutes() {
        if (responseTimeMinutes != null) {
            return responseTimeMinutes;
        }
        return calculateResponseTime();
    }

    public Long getResolutionTimeMinutes() {
        if (processingTimeMinutes != null) {
            return processingTimeMinutes;
        }
        return calculateProcessingTime();
    }

    public Long getCurrentProcessingTimeMinutes() {
        if (inProgressTime != null && LocalDateTime.now().isAfter(inProgressTime)) {
            return Duration.between(inProgressTime, LocalDateTime.now()).toMinutes();
        }
        return 0L;
    }

    public boolean isResponseTimeout() {
        Long responseTime = getResponseTimeMinutes();
        return responseTime != null && responseTime > 30; // 30分钟超时
    }

    public boolean isResolutionTimeout() {
        Long processingTime = getCurrentProcessingTimeMinutes();
        return processingTime > 120; // 2小时超时
    }

    public boolean isActive() {
        return "PENDING".equals(status) || "ASSIGNED".equals(status) || "IN_PROGRESS".equals(status);
    }

    public boolean needsAttention() {
        return isResponseTimeout() || isResolutionTimeout() || "DANGER".equals(safetyStatus) || "SOS".equals(safetyStatus);
    }

    private Long calculateResponseTime() {
        if (assignedTime != null && arrivedTime != null) {
            return Duration.between(assignedTime, arrivedTime).toMinutes();
        }
        return null;
    }

    private Long calculateProcessingTime() {
        if (arrivedTime != null && completedTime != null) {
            return Duration.between(arrivedTime, completedTime).toMinutes();
        }
        return null;
    }

    public Long calculateTotalTime() {
        if (assignedTime != null && completedTime != null) {
            return Duration.between(assignedTime, completedTime).toMinutes();
        }
        return null;
    }

    public boolean isEmergency() {
        return "CRITICAL".equals(severity) || "HIGH".equals(priority);
    }

    public String getResponderStatusDisplay() {
        switch (responderStatus) {
            case "ASSIGNED": return "已分配";
            case "ACCEPTED": return "已接受";
            case "EN_ROUTE": return "前往中";
            case "ARRIVED": return "已到达";
            case "IN_PROGRESS": return "处理中";
            case "COMPLETED": return "已完成";
            default: return responderStatus;
        }
    }

    public String getSafetyStatusDisplay() {
        switch (safetyStatus) {
            case "SAFE": return "安全";
            case "CAUTION": return "注意";
            case "DANGER": return "危险";
            case "SOS": return "紧急求救";
            default: return safetyStatus;
        }
    }

    public String getSafetyStatusColor() {
        switch (safetyStatus) {
            case "SAFE": return "success";
            case "CAUTION": return "warning";
            case "DANGER": return "danger";
            case "SOS": return "danger";
            default: return "secondary";
        }
    }
} 